<template>
  <div class="course-schedule">
    <div class="schedule-container">
      <div v-for="(schedules, date) in groupedSchedules" :key="date" class="schedule-day">
        <h3 class="date-header">{{ formatDate(date) }}</h3>
        <div class="time-slots">
          <div v-for="schedule in schedules" :key="schedule.scheduleId" class="time-slot">
            <div class="time-info">
              <span class="time">{{ schedule.startTime }} - {{ schedule.endTime }}</span>
              <span :class="['status', getStatusClass(schedule.status)]">
                {{ getStatusText(schedule.status) }}
              </span>
            </div>
            <el-button 
              type="primary" 
              size="small" 
              :disabled="schedule.status !== 0"
              @click="handleBookCourse(schedule)"
            >
              预约
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
/* eslint-disable no-undef */
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { bookCourse } from '@/api/course'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'

const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  },
  schedules: {
    type: Array,
    required: true
  }
})

const router = useRouter()

/**
 * 格式化日期显示
 * @param {string} date - 日期字符串
 * @returns {string} 格式化后的日期
 */
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

/**
 * 获取课程状态对应的文本
 * @param {number} status - 课程状态码
 * @returns {string} 状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    '-1': '已取消',
    '0': '可预约',
    '1': '不可预约'
  }
  return statusMap[status] || '未知'
}

/**
 * 获取课程状态对应的样式类
 * @param {number} status - 课程状态码
 * @returns {string} 样式类名
 */
const getStatusClass = (status) => {
  const classMap = {
    '-1': 'cancelled',
    '0': 'available',
    '1': 'unavailable'
  }
  return classMap[status] || ''
}

/**
 * 计算属性：将课程表按日期分组
 */
const groupedSchedules = computed(() => {
  const groups = {}
  props.schedules.forEach(schedule => {
    if (!groups[schedule.date]) {
      groups[schedule.date] = []
    }
    groups[schedule.date].push(schedule)
  })
  return groups
})

/**
 * 处理课程预约
 * @param {Object} schedule - 课程时间表信息
 */
const handleBookCourse = async (schedule) => {
  try {
    const appointmentData = {
      courseId: props.courseId,
      scheduleId: schedule.scheduleId,
      appointmentDate: schedule.date,
      startTime: schedule.startTime,
      endTime: schedule.endTime
    }

    // 调用预约接口
    const response = await bookCourse(appointmentData)
    
    if (response.code === 200) {
      ElMessage.success('预约成功')
      
      // 获取预约响应数据
      const orderData = response.data
      
      // 定义订单视图数据
      const ordersViewData = {
        courseId: props.courseId,
        scheduleId: schedule.scheduleId,
        appointmentDate: schedule.date,
        startTime: schedule.startTime,
        endTime: schedule.endTime,
        ordersId: orderData.ordersId
      }
      
      // 将订单数据保存到localStorage
      localStorage.setItem('currentOrderData', JSON.stringify(ordersViewData))
      
      // 跳转到订单确认页面
      router.push({
        path: '/order/confirm',
        query: { scheduleId: orderData.scheduleId }
      })
    } else {
      ElMessage.error(response.message || '预约失败')
    }
  } catch (error) {
    ElMessage.error('预约失败，请重试')
  }
}
</script>

<style scoped>
.course-schedule {
  padding: 20px;
}

.schedule-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.schedule-day {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.date-header {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.time-slots {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.time-slot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.time-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.time {
  font-size: 14px;
  color: #606266;
}

.status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
}

.status.available {
  background: #e1f3d8;
  color: #67c23a;
}

.status.unavailable {
  background: #fef0f0;
  color: #f56c6c;
}

.status.cancelled {
  background: #fef0f0;
  color: #f56c6c;
}
</style> 